package eran;

import com.google.gson.Gson;
import eran.utils.FileUtils;
import eran.vo.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

/**
 * Created by eran on 14-11-27.
 */
public class LogicMain
{
    private String mInputFolderPath;
    private String mOutputFolderPath;

    private RootVo mRootVo;


    public void initialize(String[] _args)
    {
        if (_args.length == 2)
        {
            if (!_args[0].isEmpty())
            {
                mInputFolderPath = _args[0];
            }
            if (!_args[1].isEmpty())
            {
                mOutputFolderPath = _args[1];
            }
        }
        if (mInputFolderPath == null || mOutputFolderPath == null)
        {
            System.err.println("Can't analysis mInputFolderPath||mOutputFolderPath or args length not 2");
        }
    }

    public void run()
    {
        createSubFolder();
        scanTargetFolder();
        writeSingleJsonConfig();
        writeWeekJsonConfig();
    }

    //==============================
    //==== 创建子目录
    //==============================
    private void createSubFolder()
    {
        File outPutFolder = new File(mOutputFolderPath);
        if (!outPutFolder.exists())
        {
            outPutFolder.mkdirs();
        }

        File imgFolder = new File(mOutputFolderPath + "/imgTemp");
        if (!imgFolder.exists())
        {
            imgFolder.mkdirs();
        }
        File soundFolder = new File(mOutputFolderPath + "/sound");
        if (!soundFolder.exists())
        {
            soundFolder.mkdirs();
        }
    }


    //==============================
    //==== 扫描目录
    //==============================

    private void scanTargetFolder()
    {
        mRootVo = new RootVo();
        //Root节点
        mRootVo.weekList = new ArrayList<WeekVo>();
        File rootFolder = new File(mInputFolderPath);

        //每周
        File[] allWeekFolderArray = rootFolder.listFiles();
        for (File eachWeekFolder : allWeekFolderArray)
        {
            if (eachWeekFolder.isDirectory())
            {
                WeekVo eachWeekVo = new WeekVo();
                eachWeekVo.weekIndex = Integer.parseInt(eachWeekFolder.getName());
                mRootVo.weekList.add(eachWeekVo);

                File[] allDaysFolderArray = eachWeekFolder.listFiles();
                for (File eachDayFolder : allDaysFolderArray)
                {
                    if (eachDayFolder.isDirectory())
                    {
                        //每天
                        DayVo eachDayVo = new DayVo();
                        eachDayVo.dayIndex = Integer.parseInt(eachDayFolder.getName());
                        eachWeekVo.dayList.add(eachDayVo);

                        //每张卡片
                        File[] allMovieCardFolderArray = eachDayFolder.listFiles();
                        for (File eachCardFolder : allMovieCardFolderArray)
                        {
                            if (eachCardFolder.isDirectory())
                            {
                                CardVo eachCardVo = new CardVo();
                                eachDayVo.movieCardList.add(eachCardVo);

                                analyseEachCardFolder(eachCardFolder, eachCardVo,
                                        Integer.parseInt(eachWeekFolder.getName()),
                                        Integer.parseInt(eachDayFolder.getName()),
                                        Integer.parseInt(eachCardFolder.getName()));
                            }
                        }
                    }
                }
            }
        }
    }

    //===================
    //==分析每张卡片
    //===================

    private void analyseEachCardFolder(File _eachCardFolder,
                                       CardVo _currentCardVo,
                                       int _weekIndex,
                                       int _dayIndex,
                                       int _cardIndex)
    {
        _currentCardVo.cardID = _cardIndex + _dayIndex * 100 + _weekIndex * 10000;
        File[] alllFileUnderCardFolder = _eachCardFolder.listFiles();
        for (File eachSubFile : alllFileUnderCardFolder)
        {
            if (eachSubFile.isDirectory())
            {
                System.err.println("Can't have sub folder under each card folder");
            }
            else
            {
                String fileExtensionName = FileUtils.getExtensionName(eachSubFile.getName());
                if (fileExtensionName.equals("json"))
                {
                    handleCardJSONFile(_currentCardVo, eachSubFile);
                }
                else if (fileExtensionName.equals("jpg"))
                {
                    handleCardImgFile(_currentCardVo, eachSubFile);
                }
                else if (fileExtensionName.equals("mp3"))
                {
                    handleCardMp3File(_currentCardVo, eachSubFile);
                }
                else if (fileExtensionName.equals("DS_Store"))
                {
                    //Mac垃圾文件 忽略
                }
                else
                {
                    System.err.println("Unknown File: " + eachSubFile.getName() +
                            " under Card Folder , CardID: " + _currentCardVo.cardID);
                }
            }

        }
    }

    /**
     * 处理卡片的音频文件
     * <p/>
     * 1`将Mp3文件名md5以后放到目标文件夹下的sound目录
     */
    private void handleCardMp3File(CardVo _currentCardVo, File _mp3File)
    {
        String md5 = FileUtils.getFileMD5String(_mp3File);
        _currentCardVo.cardSoundFileName = md5;

        File destFile = new File(mOutputFolderPath + "/sound/" + md5 + ".mp3");
        if (!destFile.exists())
        {
            try
            {
                Files.copy(_mp3File.toPath(), destFile.toPath());
            } catch (IOException e)
            {
                System.err.println("Can't copy Mp3 file to folder, File name is: " + _mp3File.getName());
            }
        }

    }

    /**
     * 处理卡片的图片文件
     */
    private void handleCardImgFile(CardVo _currentCardVo, File _imgFile)
    {
        String md5 = FileUtils.getFileMD5String(_imgFile);
        _currentCardVo.cardImgFileName = md5;

        File destFile = new File(mOutputFolderPath + "/imgTemp/" + md5 + ".jpg");
        if (!destFile.exists())
        {
            try
            {
                Files.copy(_imgFile.toPath(), destFile.toPath());
            } catch (IOException e)
            {
                System.err.println("Can't copy Img file to folder, File name is: " + _imgFile.getName());
            }
        }
    }

    private void handleCardJSONFile(CardVo _currentCardVo, File _jsonFile)
    {
        Gson gson = new Gson();
        String jsonSTR = "";
        BufferedReader reader;
        try
        {
            reader = new BufferedReader(new FileReader(_jsonFile));
            String tempString;
            while ((tempString = reader.readLine()) != null)
            {
                jsonSTR += tempString;
            }
            reader.close();
        } catch (IOException e)
        {
            System.err.println("Can not analyse Card Json File, CardID: " + _currentCardVo.cardID);
        }
        CardJsonVo cardJsonVo = gson.fromJson(jsonSTR, CardJsonVo.class);
        _currentCardVo.originalMsg = cardJsonVo.originalMsg;
        _currentCardVo.translateMsg = cardJsonVo.translateMsg;
    }

    //========================
    //==生成JSON Config
    //========================

    private void writeSingleJsonConfig()
    {
        Gson gson = new Gson();
        String jsonSTR = gson.toJson(mRootVo, RootVo.class);
        FileUtils.writeStringToFile(jsonSTR, mOutputFolderPath + "/MovieCardConfig.json");

    }

    /**
     * 以每周作为一个节点生成一个单独的JSON文件
     */
    private void writeWeekJsonConfig()
    {
        for (WeekVo eachWeekVo : mRootVo.weekList)
        {
            Gson gson = new Gson();
            String jsonSTR = gson.toJson(eachWeekVo, WeekVo.class);
            FileUtils.writeStringToFile(jsonSTR, mOutputFolderPath + "/" + eachWeekVo.weekIndex + ".json");
        }
    }


}
